package com.gogowan.agroenterprise.supply;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
import com.gogowan.agroenterprise.R;
import com.gogowan.agroenterprise.base.BaseActivity;
import com.gogowan.agroenterprise.contorl.MyAsyncTask;
import com.gogowan.agroenterprise.model.IntegrateQuestInfo;
import com.gogowan.agroenterprise.model.Message;
import com.gogowan.agroenterprise.model.ResultInfo;
import com.gogowan.agroenterprise.model.SupplyDemandDescInfo;
import com.gogowan.agroenterprise.supply.utils.Files;
import com.gogowan.agroenterprise.supply.utils.Net;
import com.gogowan.agroenterprise.supply.utils.SupplyAndDemandUtils;
import com.gogowan.agroenterprise.utils.Utils;

/**
 * 查看我的供应详细信息
 * @author Maniac
 * 2012-12-21
 */
public class CheckMySupplyActivity extends BaseActivity{
	
	private static final int EDIT = 100;
	private TextView title,productName,introduction,keywords,productInfo,deadline;
	private Gallery gallery;
	private LinearLayout galleryLinear;
	private Button editBtn, deleteBtn;
	
	private ProgressDialog progressDialog;
	
	private SharedPreferences preferences;
	private long enterpriseId;
	private long sdID;
	private String infoString;
	private SupplyDemandDescInfo supplyDemandDescInfo; //传过来的信息
	private String titleforCallback;
	
	public static HashMap<String, Bitmap> imagesCache = new HashMap<String, Bitmap>(); // 图片缓存
	public static ImageAdapter imageAdapter;
	private int num = 0;
	List<String> urls = new ArrayList<String>(); // 所有图片地址List

	List<String> url = new ArrayList<String>(); // 需要下载图片的url地址
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.supply_check_mysupply);
		
		title = (TextView)findViewById(R.id.check_mysupply_title);
		productName = (TextView)findViewById(R.id.check_mysupply_product_name);
		introduction = (TextView)findViewById(R.id.check_mysupply_introduction);
		keywords = (TextView)findViewById(R.id.check_mysupply_keywords);
		productInfo = (TextView)findViewById(R.id.check_mysupply_product_info);
		gallery = (Gallery)findViewById(R.id.check_mysupply_gallery);
		galleryLinear = (LinearLayout)findViewById(R.id.check_mysupply_gallerylinear);
		deadline = (TextView)findViewById(R.id.check_mysupply_date);
		editBtn = (Button)findViewById(R.id.check_mysupply_edit);
		deleteBtn = (Button)findViewById(R.id.check_mysupply_delete);
		
		preferences = getSharedPreferences("LoginINfo", MODE_PRIVATE);
		enterpriseId = preferences.getLong("enterpriseid", 0);
		
		Files.mkdir(this);
		
		Intent intent = getIntent();
		infoString = intent.getStringExtra("myDetail");
		
		supplyDemandDescInfo = (SupplyDemandDescInfo)Utils.fromJSON(infoString, SupplyDemandDescInfo.class);
		if (supplyDemandDescInfo == null) {
			return;
		} else {
			title.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getTitle().toString().trim()));
			titleforCallback = supplyDemandDescInfo.getTitle().toString().trim();
			try {
				productName.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getMaterialFullName().toString().trim()));
			} catch (Exception e) {
				productName.setText("数据出错");
				e.printStackTrace();
			}
			introduction.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getIntroduction().toString().trim()));
			keywords.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getKeyWords().toString().trim()));
			productInfo.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getDescription().toString()));
			deadline.setText(SupplyAndDemandUtils.ToDBC(supplyDemandDescInfo.getTimeDown().toString().trim()));
			
			sdID = supplyDemandDescInfo.getSdID();
			
			if (supplyDemandDescInfo.getPhotoList() == null || supplyDemandDescInfo.getPhotoList().size() == 0) {
				galleryLinear.setVisibility(View.GONE);
			} else {
				Bitmap image = BitmapFactory.decodeResource(getResources(),
						R.drawable.background_main);
				imagesCache.put("background_non_load", image); // 设置缓存中默认的图片
				
				for (int i = 0; i < supplyDemandDescInfo.getPhotoList().size(); i++) {
					urls.add(supplyDemandDescInfo.getPhotoList().get(i).getPhotoPathNormal());
				}
				
				imageAdapter = new ImageAdapter(urls, this);
				gallery.setAdapter(imageAdapter);
				
				gallery.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						// TODO Auto-generated method stub
						
					}
				});
				
				gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						num = arg2;
						Log.i("mahua", "ItemSelected==" + arg2);
						GalleryWhetherStop();
					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
						// TODO Auto-generated method stub

					}
				});
			}
		}
		
		
		deleteBtn.setOnClickListener(deleteBtnCallback);
		editBtn.setOnClickListener(editBtnCallback);
	}
	
	/**
	 * 删除按钮点击事件
	 */
	public Button.OnClickListener deleteBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			
			AlertDialog alert = new AlertDialog.Builder(CheckMySupplyActivity.this)
			.setTitle("警告")
			.setMessage("确实要删除这条供应信息吗?").setCancelable(false)
					.setNegativeButton("否", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							// do nothing
						}
					})
					.setPositiveButton("是", new AlertDialog.OnClickListener() {
						public void onClick(DialogInterface dialog,
								int whichButton) {
							IntegrateQuestInfo integrateQuestInfo = new IntegrateQuestInfo();
							integrateQuestInfo.setEnterpriseID(enterpriseId);
							integrateQuestInfo.setSdID(sdID);

							progressDialog = ProgressDialog.show(CheckMySupplyActivity.this,
									getString(R.string.alert_title),
									getString(R.string.alert_message), true, false);
							
							DeleteSupplyAsyn deleteSupplyAsyn = new DeleteSupplyAsyn();
							deleteSupplyAsyn.execute(integrateQuestInfo);
						}
					}).create();
			alert.show();
			
			
			
		}
		
	};
	
	/**
	 * 编辑按钮点击事件
	 */
	public Button.OnClickListener editBtnCallback = new Button.OnClickListener(){

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(CheckMySupplyActivity.this,MySupplyDetailActivity.class);
			intent.putExtra("myDetail", infoString);
			startActivityForResult(intent, EDIT);
			Utils.randomAnim(CheckMySupplyActivity.this);
		}
	};
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 100) {
			if (requestCode == EDIT) {
				String newString = data.getStringExtra("editedInfo");
				SupplyDemandDescInfo supplyDemandDescInfo = (SupplyDemandDescInfo) Utils
						.fromJSON(newString, SupplyDemandDescInfo.class);
				
				title.setText(supplyDemandDescInfo.getTitle().toString().trim());
				titleforCallback = supplyDemandDescInfo.getTitle().toString().trim();
				try {
					productName.setText(supplyDemandDescInfo.getMaterialFullName().toString().trim());
				} catch (Exception e) {
					productName.setText("数据出错");
					e.printStackTrace();
				}
				introduction.setText(supplyDemandDescInfo.getIntroduction().toString().trim());
				keywords.setText(supplyDemandDescInfo.getKeyWords().toString().trim());
				productInfo.setText(supplyDemandDescInfo.getDescription().toString());
				deadline.setText(supplyDemandDescInfo.getTimeDown().toString().trim());
				
				Intent intent = new Intent();
				intent.putExtra("title", titleforCallback);
				setResult(100,intent);
				CheckMySupplyActivity.this.finish();
				Utils.randomAnim(CheckMySupplyActivity.this);
			}
		} else if (resultCode == 200) {
			setResult(200);
			CheckMySupplyActivity.this.finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	
	/**
	 * 如果此条数据已编辑，按下返回键时应刷新列表页面的title
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			Intent intent = new Intent();
			intent.putExtra("title", titleforCallback);
			setResult(100,intent);
			CheckMySupplyActivity.this.finish();
			Utils.randomAnim(CheckMySupplyActivity.this);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}



	/**
	 * 删除当前信息异步
	 * @author Maniac
	 */
	private class DeleteSupplyAsyn extends MyAsyncTask{

		@Override
		protected void onPostExecute(Object res) {
			if (res == null || res.equals("")) {
				Toast.makeText(CheckMySupplyActivity.this, getString(R.string.server_error), Toast.LENGTH_LONG).show();
			} else {
				
				Message message = (Message) Utils.fromJSON((String) res, Message.class);
				String string = Utils.getMessageContent(message);
				if (string == null || string.equals("")) {
					Toast.makeText(CheckMySupplyActivity.this, getString(R.string.analyse_error), Toast.LENGTH_LONG).show();
				} else {
					ResultInfo resultInfo = (ResultInfo)Utils.fromJSON(string, ResultInfo.class);
					int result = resultInfo.getResult();
					if (result == 6410) {
						
						//返回列表activity 并删除该项
						setResult(200);
						
						Toast.makeText(CheckMySupplyActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
						CheckMySupplyActivity.this.finish();
						Utils.randomAnim(CheckMySupplyActivity.this);
						
					} else {
						Toast.makeText(CheckMySupplyActivity.this, resultInfo.getResultinfo(), Toast.LENGTH_LONG).show();
					}
				}
			}
			progressDialog.dismiss();
			super.onPostExecute(res);
		}

		@Override
		protected Object doInBackground(Object... params) {
			IntegrateQuestInfo request = (IntegrateQuestInfo)params[0];
			String json = Utils.toJSON(request);
			Message message = new Message(6400, true, json);
			String res = Utils.postCommit(getString(R.string.first_url)
					+ getString(R.string.first_url_page), message);
			return res;
		}
	}
	
	/**
	 * 判断Gallery滚动是否停止,如果停止则加载当前页面的图片
	 */
	private void GalleryWhetherStop() {
		Runnable runnable = new Runnable() {
			public void run() {
				try {
					int index = 0;
					index = num;
					Thread.sleep(1000);
					if (index == num) {
						url.add(urls.get(num));
						if (num != 0 && urls.get(num - 1) != null) {
							url.add(urls.get(num - 1));
						}
						if (num != urls.size() - 1 && urls.get(num + 1) != null) {
							url.add(urls.get(num + 1));
						}
						android.os.Message m = new android.os.Message();
						m.what = 1;
						mHandler.sendMessage(m);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		new Thread(runnable).start();
	}

	// 加载图片的异步任务
	class LoadImageTask extends AsyncTask<String, Void, Bitmap> {

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
		}

		@Override
		protected Bitmap doInBackground(String... params) {
			Bitmap bitmap = null;
			try {
				String url = params[0];
				boolean isExists = Files.compare(url);
				if (isExists == false) {
					Net net = new Net();
					byte[] data = net.downloadResource(CheckMySupplyActivity.this, url);
					bitmap = BitmapFactory
							.decodeByteArray(data, 0, data.length);
					imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
					Files.saveImage(url, data);
				} else {
					byte[] data = Files.readImage(url);
					bitmap = BitmapFactory
							.decodeByteArray(data, 0, data.length);
					imagesCache.put(url, bitmap); // 把下载好的图片保存到缓存中
				}

				android.os.Message m = new android.os.Message();
				m.what = 0;
				mHandler.sendMessage(m);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return bitmap;
		}
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			try {
				switch (msg.what) {
				case 0: {
					imageAdapter.notifyDataSetChanged();
					break;
				}
				case 1: {
					for (int i = 0; i < url.size(); i++) {
						LoadImageTask task = new LoadImageTask();// 异步加载图片
						task.execute(url.get(i));
						Log.i("mahua", url.get(i));
					}
					url.clear();
				}
				}
				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	public class ImageAdapter extends BaseAdapter {
		public final BaseAdapter Adapter = null;
		private List<String> imageUrls; // 图片地址list
		private Context context;
		int mGalleryItemBackground;

		public ImageAdapter(List<String> imageUrls, Context context) {
			this.imageUrls = imageUrls;
			this.context = context;
			// /*
			// * 使用在res/values/attrs.xml中的<declare-styleable>定义 的Gallery属性.
			// */
			TypedArray a = context.obtainStyledAttributes(R.styleable.Gallery1);
			/* 取得Gallery属性的Index id */
			mGalleryItemBackground = a.getResourceId(
					R.styleable.Gallery1_android_galleryItemBackground, 0);
			/* 让对象的styleable属性能够反复使用 */
			a.recycle();
		}

		public int getCount() {
			return imageUrls.size();
		}

		public Object getItem(int position) {
			return imageUrls.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			Bitmap image;
			
			ImageView view = new ImageView(context);
			image = imagesCache.get(imageUrls.get(position));
			// 从缓存中读取图片
			if (image == null) {
				image = imagesCache.get("background_non_load");
			}
			// 设置所有图片的资源地址
			view.setImageBitmap(image);
			view.setScaleType(ImageView.ScaleType.FIT_XY);
			view.setLayoutParams(new Gallery.LayoutParams(240, 320));
			view.setBackgroundResource(mGalleryItemBackground);
			/* 设置Gallery背景图 */
			return view;
		}
	}
}
